// 依赖
const koa = require('koa');
const cors = require('koa2-cors');
const session = require('koa-session');
const bodyParser = require('koa-bodyparser');
require('module-alias/register');


// 自定义
const config = require('_/config');
const resFormat = require('lib/middleware/resFormat.js');
const requiredParams = require('lib/middleware/requiredParams.js');
const jwtToken = require('lib/utils/jwtToken.js');


const app = new koa();

app.proxy = true;

/**
 * 跨域
 */
app.use(cors({
  credentials: true
}));

/**
 * koa-session
 */
 app.keys = ['secret of koa-session'];
 app.use(session({
   key: 'koa:sess',
   maxAge: 1000 * 60 * 60 * 24 * 7,
   overwrite: true,
   httpOnly: true,
   signed: true,
   rolling: true, // 是否每次响应时刷新Session的有效期, 刷新的提前是token还未失效
   renew: false,
 }, app));

/**
 * 映射静态目录
 */
app.use(require('koa-static')(__dirname + config.statusDirPath));

/**
 * 注册自定义中间件
 */
app.use(resFormat());
app.use(requiredParams());

/**
 * 拦截
 */
app.use(async (ctx, next) => {
  if (ctx.path === '/favicon.ico') return;

  // 打印接口请求Time
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`Method: ${ctx.method} --> Url: ${ctx.url} --> Time: ${ms}ms`)
});

/**
 * 处理post参数
 */
app.use(bodyParser());

/**
 * 验证Token
 */
app.use(jwtToken.verifyToken());


/** 路由
 * router.allowedMethods()作用:这是官方文档的推荐用法为全局配置,我们可以
 * 看到router.allowedMethods()用在了路由匹配 router.routes()之后,所以
 * 在当所有路由中间件最后调用.此时根据 ctx.status 设置 response 响应头
 * 主要是处理status为空或者404情况的404情况的
 * https://www.jianshu.com/p/fef91266a44c
 */
app.use(require('./src/routes/files.js').routes(), require('./src/routes/files.js').allowedMethods());
app.use(require('./src/routes/user.js').routes(), require('./src/routes/user.js').allowedMethods());
app.use(require('./src/routes/place.js').routes(), require('./src/routes/place.js').allowedMethods());
app.use(require('./src/routes/dictionary.js').routes(), require('./src/routes/dictionary.js').allowedMethods());
app.use(require('./src/routes/package.js').routes(), require('./src/routes/package.js').allowedMethods());
app.use(require('./src/routes/record.js').routes(), require('./src/routes/record.js').allowedMethods());
app.use(require('./src/routes/record.js').routes(), require('./src/routes/record.js').allowedMethods());
app.use(require('./src/routes/car.js').routes(), require('./src/routes/car.js').allowedMethods());
app.use(require('./src/routes/blackList.js').routes(), require('./src/routes/blackList.js').allowedMethods());
app.use(require('./src/routes/wx.js').routes(), require('./src/routes/wx.js').allowedMethods());
app.use(require('./src/routes/reservation.js').routes(), require('./src/routes/reservation.js').allowedMethods());

module.exports = app;

